package com.pan.admin.common.utils.file;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.internal.OSSHeaders;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.oss.model.StorageClass;
import com.gitee.apanlh.util.algorithm.digest.DigestType;
import com.gitee.apanlh.util.algorithm.digest.SHA;
import com.gitee.apanlh.util.io.IOUtils;
import com.gitee.apanlh.util.log.Log;
import com.pan.admin.common.constant.Constants;
import com.pan.admin.common.exception.file.FileNameLengthLimitExceededException;
import com.pan.admin.common.exception.file.FileSizeLimitExceededException;
import com.pan.admin.common.exception.file.InvalidExtensionException;
import com.pan.admin.common.utils.DateUtils;
import com.pan.admin.common.utils.DictUtils;
import com.pan.admin.common.utils.StringUtils;
import com.pan.admin.common.utils.file.model.FileUploadResult;
import com.pan.admin.common.utils.uuid.Seq;
import com.pan.admin.framework.config.AdminConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Objects;

/**
 * 文件上传工具类
 *
 *
 */
public class FileUploadUtils {
    /**
     * 默认大小 50M
     */
    public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;

    /**
     * 默认的文件名最大长度 100
     */
    public static final int DEFAULT_FILE_NAME_LENGTH = 100;

    /**
     * 默认上传的地址
     */
    private static String defaultBaseDir = AdminConfig.getProfile();

    public static void setDefaultBaseDir(String defaultBaseDir) {
        FileUploadUtils.defaultBaseDir = defaultBaseDir;
    }

    public static String getDefaultBaseDir() {
        return defaultBaseDir;
    }

    /**
     * 以默认配置进行文件上传
     *
     * @param file 上传的文件
     * @return 文件名称
     * @throws Exception
     */
    public static final String upload(MultipartFile file) throws IOException {
        try {
            return upload(getDefaultBaseDir(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, false);
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }

    /**
     * 根据文件路径上传
     *
     * @param baseDir 相对应用的基目录
     * @param file    上传的文件
     * @return 文件名称
     * @throws IOException
     */
    public static final String upload(String baseDir, MultipartFile file) throws IOException {
        try {
            return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, false);
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }

    /**
     * 根据文件路径上传
     *
     * @param baseDir 相对应用的基目录
     * @param file    上传的文件
     * @return 文件名称
     * @throws IOException
     */
    public static final String upload(String baseDir, MultipartFile file, boolean hashFileName) throws IOException {
        try {
            return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, hashFileName);
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }

    /**
     * 文件上传
     *
     * @param baseDir          相对应用的基目录
     * @param file             上传的文件
     * @param allowedExtension 上传文件类型
     * @return 返回上传成功的文件名
     * @throws FileSizeLimitExceededException       如果超出最大大小
     * @throws FileNameLengthLimitExceededException 文件名太长
     * @throws IOException                          比如读写文件出错时
     * @throws InvalidExtensionException            文件校验异常
     */
    public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension)
            throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
            InvalidExtensionException {
        return upload(baseDir, file, allowedExtension, false);
    }

    /**
     * 文件上传
     *
     * @param baseDir          相对应用的基目录
     * @param file             上传的文件
     * @param allowedExtension 上传文件类型
     * @return 返回上传成功的文件名
     * @throws FileSizeLimitExceededException       如果超出最大大小
     * @throws FileNameLengthLimitExceededException 文件名太长
     * @throws IOException                          比如读写文件出错时
     * @throws InvalidExtensionException            文件校验异常
     */
    public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension, boolean hashFileName)
            throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
            InvalidExtensionException {
        int fileNamelength = Objects.requireNonNull(file.getOriginalFilename()).length();
        if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
            throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
        }

        assertAllowed(file, allowedExtension);
        //  自动生产带时间戳
        String fileName = extractFilename(file, true, hashFileName);

        String absPath = getAbsoluteFile(baseDir, fileName).getAbsolutePath();
        file.transferTo(Paths.get(absPath));
        return getPathFileName(baseDir, fileName);
    }

    /**
     * 编码文件名
     */
    public static final String extractFilename(MultipartFile file, boolean hasCreateTime, boolean hashFileName) {
        //  带时间地址路径
        if (hasCreateTime) {
            return StringUtils.format("{}/{}_{}.{}", DateUtils.dateTime(),
                    Seq.getId(Seq.uploadSeqType), FilenameUtils.getBaseName(hashFileName ? SHA.create(DigestType.SHA_1).digestToHex(file.getOriginalFilename()) : file.getOriginalFilename()), getExtension(file));
        }
        //  不带时间地址路径
        return StringUtils.format("{}_{}.{}", Seq.getId(Seq.uploadSeqType), FilenameUtils.getBaseName(hashFileName ? SHA.create(DigestType.SHA_1).digestToHex(file.getOriginalFilename()) : file.getOriginalFilename()), getExtension(file));
    }

    public static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException {
        File desc = new File(uploadDir + File.separator + fileName);

        if (!desc.exists()) {
            if (!desc.getParentFile().exists()) {
                desc.getParentFile().mkdirs();
            }
        }
        return desc;
    }

    public static final String getPathFileName(String uploadDir, String fileName) throws IOException {
        int dirLastIndex = AdminConfig.getProfile().length() + 1;
        String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
        return Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + fileName;
    }

    /**
     * 文件大小校验
     *
     * @param file 上传的文件
     * @return
     * @throws FileSizeLimitExceededException 如果超出最大大小
     * @throws InvalidExtensionException
     */
    public static final void assertAllowed(MultipartFile file, String[] allowedExtension)
            throws FileSizeLimitExceededException, InvalidExtensionException {
        long size = file.getSize();
        if (size > DEFAULT_MAX_SIZE) {
            throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024);
        }

        String fileName = file.getOriginalFilename();
        String extension = getExtension(file);
        if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) {
            if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION) {
                throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension,
                        fileName);
            } else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION) {
                throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension,
                        fileName);
            } else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION) {
                throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension,
                        fileName);
            } else if (allowedExtension == MimeTypeUtils.VIDEO_EXTENSION) {
                throw new InvalidExtensionException.InvalidVideoExtensionException(allowedExtension, extension,
                        fileName);
            } else {
                throw new InvalidExtensionException(allowedExtension, extension, fileName);
            }
        }
    }

    /**
     * 判断MIME类型是否是允许的MIME类型
     *
     * @param extension
     * @param allowedExtension
     * @return
     */
    public static final boolean isAllowedExtension(String extension, String[] allowedExtension) {
        for (String str : allowedExtension) {
            if (str.equalsIgnoreCase(extension)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     * @return 后缀名
     */
    public static final String getExtension(MultipartFile file) {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isEmpty(extension)) {
            extension = MimeTypeUtils.getExtension(Objects.requireNonNull(file.getContentType()));
        }
        return extension;
    }

    /**
     *  阿里云oss上传
     *
     *  @param  content  内容
     *  @param  fileName 文件名称
     *  @return FileUploadResult 返回上传成功对象
     */
    public static final FileUploadResult aliyunOssUpload(byte[] content, String fileName) throws Exception {
        String endpoint = DictUtils.getDictValue("aliyun_oss", "endpoint");
        String key = DictUtils.getDictValue("aliyun_oss", "key");
        String secret = DictUtils.getDictValue("aliyun_oss", "secret");

        DefaultCredentialProvider credentialsProvider = CredentialsProviderFactory.newDefaultCredentialProvider(key, secret);
        //  填写Bucket名称，例如examplebucket。
        String bucketName = DictUtils.getDictValue("aliyun_oss", "bucket_name");
        //  图片上传路径
        String imageUploadPath = DictUtils.getDictValue("tencent_cos", "image_upload_path");
        //  填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = DictUtils.getDictValue("aliyun_oss", "image_upload_path") + "/" + fileName;

        //  上传成功返回对象
        FileUploadResult fileUploadResult = new FileUploadResult();
        String domainPath = DictUtils.getDictValue("aliyun_oss", "domain");
        fileUploadResult.setDomainPath(domainPath);
        //  添加后缀
        if (!fileUploadResult.getDomainPath().endsWith("/")) {
            fileUploadResult.setDomainPath(fileUploadResult.getDomainPath() + "/");
        }
        fileUploadResult.setUploadPath(imageUploadPath);
        fileUploadResult.setUploadFileName(fileName);
        fileUploadResult.setUploadFullPath(objectName);

        //  创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(content));

            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            //  设置公共读
            metadata.setObjectAcl(CannedAccessControlList.PublicRead);
            putObjectRequest.setMetadata(metadata);

            // 上传字符串。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        } catch (Exception e) {
            throw e;
        }  finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return fileUploadResult;
    }

    /**
     *  腾讯云cos
     *
     *  @param  content  内容
     *  @param  fileName 文件名称
     *  @return FileUploadResult 返回上传成功对象
     */
    public static final FileUploadResult tencentCosUpload(byte[] content, String fileName) throws Exception {
        String endpoint = DictUtils.getDictValue("tencent_cos", "endpoint");
        String key = DictUtils.getDictValue("tencent_cos", "key");
        String secret = DictUtils.getDictValue("tencent_cos", "secret");
        //  填写地区名称
        String region = DictUtils.getDictValue("tencent_cos", "region");
        //  填写Bucket名称
        String bucketName = DictUtils.getDictValue("tencent_cos", "bucket_name");
        //  图片上传路径
        String imageUploadPath = DictUtils.getDictValue("tencent_cos", "image_upload_path");
        //  填写Object完整路径
        String objectName = imageUploadPath + "/" + fileName;
        //  上传路径
        COSClient cosClient = null;

        //  上传成功返回对象
        FileUploadResult fileUploadResult = new FileUploadResult();
        fileUploadResult.setDomainPath(endpoint);
        //  添加后缀
        if (!fileUploadResult.getDomainPath().endsWith("/")) {
            fileUploadResult.setDomainPath(fileUploadResult.getDomainPath() + "/");
        }
        fileUploadResult.setUploadPath(imageUploadPath);
        fileUploadResult.setUploadFileName(fileName);
        fileUploadResult.setUploadFullPath(objectName);

        try {
            COSCredentials cred = new BasicCOSCredentials(key, secret);
            // ClientConfig 中包含了后续请求 COS 的客户端设置：
            ClientConfig clientConfig = new ClientConfig();
            // 设置 bucket 的地域
            // COS_REGION 请参见 https://cloud.tencent.com/document/product/436/6224

            //  找到关联枚举
            com.tencentcloudapi.common.profile.Region findRegion = null;
            com.tencentcloudapi.common.profile.Region[] values = com.tencentcloudapi.common.profile.Region.values();
            for (com.tencentcloudapi.common.profile.Region value : values) {
                if (region.contains(value.getValue())) {
                    findRegion = value;
                }
            }

            clientConfig.setRegion(new com.qcloud.cos.region.Region(findRegion.getValue()));
            cosClient = new COSClient(cred, clientConfig);

            ByteArrayInputStream inputStream = IOUtils.toByteInput(content);
            com.qcloud.cos.model.ObjectMetadata objectMetadata = new com.qcloud.cos.model.ObjectMetadata();
            objectMetadata.setContentLength(content.length);

            com.qcloud.cos.model.PutObjectRequest putObjectRequest = new com.qcloud.cos.model.PutObjectRequest(bucketName, objectName, inputStream, objectMetadata);
            // 设置存储类型（如有需要，不需要请忽略此行代码）, 默认是标准(Standard), 低频(standard_ia)
            // 更多存储类型请参见 https://cloud.tencent.com/document/product/436/33417
            putObjectRequest.setStorageClass(com.qcloud.cos.model.StorageClass.Standard);

            com.qcloud.cos.model.PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            String requestId = putObjectResult.getRequestId();
        } catch (Exception e) {
            Log.get().error("{}", e.getMessage(), e);
            throw e;
        }  finally {
            if (cosClient != null) {
                cosClient.shutdown();
            }
        }
        return fileUploadResult;
    }
}
